/******************************************************************************/
/** \file main.c
 **
 ** A detailed description is available at
 ** @link Sample Group Some description @endlink
 **
 **   - 2017-05-17  1.0  cj First version for Device Driver Library of Module.
 **
 ******************************************************************************/

/******************************************************************************
 * Include files
 ******************************************************************************/
#include "ddl.h"
#include "uart.h"
#include "gpio.h"
#include "sysctrl.h"
#include "lpm.h"
#include "wdt.h"

//c库
#include "stdbool.h"


//	用户库文件
#include "led.h"
#include "mock_key.h"
#include "delay.h"
#include "uart_api.h"
#include "CAT1.h"
#include "QG_driver.h"
#include "timer_api.h"
#include "rtc_api.h"
#include "adc_api.h"
#include "wdt_api.h"
#include "adc_api.h"


#define LOW_POWER_ENABLE



extern uint8_t UT0_IDLE_FLAG;
extern uint8_t UT0_RX_COUNT;
extern unsigned char UT0_RX_BUF[UT0_RX_MAX_LEN];
extern unsigned char UT0_TX_BUF[UT0_TX_MAX_LEN];
extern uint16_t UT0_RX_STA;   						//接收数据状态

extern char dataToSend[SEND_MAX_LEN];

extern uint8_t pre_QG_state;	//上一次驱狗功能状态

extern uint8_t QG_state_recover;   //报警恢复标志

extern char device_imei[16];   // IMEI固定15字符，这里加上了结束符

// extern uint8_t wakeup_from_rtc_interval; //RTC唤醒标志
extern uint8_t wakeup_from_rtc_doki;      //RTC闹钟唤醒标志

extern uint8_t wakeup_from_RI; //RI中断唤醒标志

extern uint8_t CAT1_state_low_power;	//0未进入低功耗，1已进入低功耗

extern uint8_t reset_flag;

extern volatile uint8_t QG_timer_start;
extern volatile uint8_t QG_state_start;
extern volatile int8_t timer_shield_observe;
extern volatile uint8_t active_during_watch_flag;
extern volatile uint16_t active_int_counter;

void hardware_init()
{
    //调试串口初始化
	uart1_init(115200);
	//CAT1通信串口初始化
	uart0_init(115200);
	
	// timer3_init(37500);  //Timer3 配置; 16分频,周期37500-->37500*(1/24M) * 64 = 100000us = 100ms

    // Debug_Printf("\r\n**************enter rtc init************");
    rtc_init();                     //RTC初始化
	// Debug_Printf("\r\n**************exit rtc init************");

	adc_battery_init();
	led_init();             //led初始化
	mock_key_init();        //模拟开关初始化
    CAT1_MAIN_DTR_init();   //CAT1模组通过引脚唤醒初始化
    CAT1_MAIN_RI_init();    //CAT1模组主动唤醒引脚初始化
	CAT1_PWRKEY_init();     //CAT1模组开关控制初始化
	CAT1_TPS_init();        //CAT1模组通电控制初始化
    QG_driver_init();       //QG驱动初始化

    QG_disperse_init();     //模拟红外引脚初始化

}

//int main()
//{
//    // QG_disperse_init();     //模拟红外引脚初始化
//    // //调试串口初始化
//	// uart1_init(115200);
//	// //CAT1通信串口初始化
//	// uart0_init(115200);
//    void hardware_init();
//	CAT1_TPS_set(ON);               //4g通电
//	
//    while (CAT1_PWRKEY_set(ON) != 1)
//    {
//        delay1ms(100);
//        Debug_Printf("4g power open fail\r\n");
//    }
//    sendCommand("AT+QCCID\r\n", "OK", 10, 2);
//	
//	while(1)
//	{
//		;
//	}
//}

uint8_t getIMEI()
{
    if (device_imei == NULL || strlen(device_imei) == 0)
    {
        char resultResp[256] = {0}; // 用于存储AT命令响应
        // ============== IMEI 采集 ==============
        memset(resultResp, 0, sizeof(resultResp));
        if (!sendCommandDetail("AT+CGSN=1\r\n", "OK", resultResp, 100, 2)) {
            Debug_Printf("\r\n[ERR] AT+CGSN=1 failed");
            return 0;
        }

        // 逐行搜索CGSN响应
        char *line = strtok(resultResp, "\n");
        while (line) {
            if (strstr(line, "+CGSN:")) {
                // 格式: +CGSN: "864784074801055"
                char *start = strchr(line, '\"');
                char *end = start ? strchr(start + 1, '\"') : NULL;
                
                if (start && end) {
                    size_t len = end - start - 1;
                    if (len > 15) len = 15;
                    strncpy(device_imei, start + 1, len);
                    device_imei[len] = '\0';
                    break;
                }
            }
            line = strtok(NULL, "\n");
        }

        if (strlen(device_imei) != 15) {
            Debug_Printf("\r\n[ERR] Invalid IMEI: %s", device_imei);
            return 0;
        }
    }    
    return 1;
}

void CAT1_config_init()
{
    CAT1_TPS_set(OFF);               //4g断电通电
    delay1ms(1000);
    CAT1_TPS_set(ON);               //4g通电
    //开机
    while (CAT1_PWRKEY_set(ON) != 1)
    {
        delay1ms(100);
        Debug_Printf("4g power open fail\r\n");
    }
    //0x6200000000, 0x7FFFFFFFFFFFFFFF，0x1E200000000, (0x8000000000 band 40) 0x4(band 3) 0x80(B8) 0x8000000004
    if (sendCommand("AT+QCFG=\"band\",0,0x8000000004\r\n", "OK", 10, 2))
    {
        Gpio_SetIO(APP_LED_PORT, APP_LED_PIN); //LED亮起
    }

	sendCommand("AT+QCCID\r\n", "OK", 10, 2);
    sendCommand("AT+COPS=0\r\n", "OK", 10, 2);
    delay1ms(1000);
    //配置RI引脚
    NT26K_ConfigureDefault();
    Debug_Printf("start MQTT conn...\r\n");
    //连接MQTT服务
    while (!NT26K_Connect_MQTT())
        delay1ms(100);
    //订阅MQTT指令下发主题
    while (!NT26K_Subscribe())
        delay1ms(100);
    //CAT1模组自检
    NT26K_selfTest();
    //发送设备信息
    Debug_Printf("start send device info...\r\n");
    NT26K_sendDeviceInfo();
    NT26K_sendDeviceSignal();
    // sendCommand("AT+QCELL?\r\n", "OK", 10, 2);
    Gpio_ClrIO(APP_LED_PORT, APP_LED_PIN); //LED亮起
}

 int32_t main(void)
 {

 	delay1ms(2000);					//防止进入低功耗后刷入不了程序
 	hardware_init();                //外设初始化
    wdt_reset_init();               //看门狗初始化
 	CAT1_TPS_set(ON);               //4g通电
    CAT1_config_init();             //CAT1模组配置初始化
    sendCommand("AT+QCELL?\r\n", "OK", 10, 2);
    sendCommand("AT+QCFG=\"urcdelay\", 1\r\n", "OK", 10, 2);
 	
    // Gpio_SetIO(APP_LED_SYS_PORT, APP_LED_SYS_PIN); //LED亮起

    unsigned char *dataPtr = NULL;
    while(1)
    {   
        Wdt_Feed();   // 喂狗   3.28后没有喂狗就会重置
        // sendCommand("AT+QURCCFG=\"urcport\"\r\n", "OK", 10, 2);
     //    CAT1_RESET_set(OFF); //拉低复位引脚，复位CAT1模组
     //    //轮询是否有消息能接收
     //    CAT1_MAIN_DTR_set(OFF);
     //    // delay1ms(52); //等待CAT1模组进入传输模式
     //    dataPtr = NT26K_GetData(2);
     //    if(dataPtr != NULL)
     //        Resolve_Rev(dataPtr);
     //    CAT1_MAIN_DTR_set(ON); //重新拉高，防止CAT1进不了低功耗
        //cat1有数据传达
        // Debug_Printf("\r\nstate_start:%d, pre_state: %d, QG_state_recover: %d, timer_shield_observe: %d, timer_start: %d, active_during_watch_flag: %d,\
        //     active_int_counter: %d\r\n"
        // , QG_state_start, pre_QG_state, QG_state_recover, timer_shield_observe, QG_timer_start, active_during_watch_flag, active_int_counter);
        if (wakeup_from_RI == 1)
        {
            wakeup_from_RI = 0; //清除RI中断唤醒标志
            //轮询是否有消息能接收
            dataPtr = NT26K_GetData(150);
            if(dataPtr != NULL)
                Resolve_Rev(dataPtr);
            CAT1_state_low_power = 0;
            CAT1_MAIN_DTR_set(ON);//重新拉高，防止CAT1进不了低功耗
         //    Debug_Printf("\r\nwakeup from RI...\r\n");
        }
        //上传心跳包时间触发，主动唤醒模块上传数据
        if (wakeup_from_rtc_doki == 1)
        {
            CAT1_MAIN_DTR_set(OFF);//拉低唤醒CAT1模组
            delay1ms(55);
            if (sendCommand("AT\r\n", "OK", 10, 2))
            {
                getIMEI();
                memset(dataToSend, 0, SEND_MAX_LEN);
                float batteryVal = get_batteryVal();
                char band_info[50] = {0};
                NT26K_getNetworkBand(band_info);
                uint8_t len = snprintf(dataToSend, SEND_MAX_LEN, 
                    "{\"switch_power\":%d,\"disperse_state\":%d, \"IMEI\":\"%s\", \"battery_voltage\":%f, \"band_info\":\"%s\"}", 
                    QG_getPowerState(), QG_info.state, device_imei, batteryVal, band_info);
                NT26K_SendData("upload_data_flag", dataToSend);
                // NT26K_sendDeviceSignal();   //定时上传信号数据
                wakeup_from_rtc_doki = 0; //清除RTC闹钟唤醒标志
                CAT1_state_low_power = 0;
            }
 //           if(0 == i)
 //           {
 //               Gpio_ClrIO(APP_LED_SYS_PORT, APP_LED_SYS_PIN);  //LED翻转
 //               i++;
 //           }
 //           else
 //           {
 //               Gpio_SetIO(APP_LED_SYS_PORT, APP_LED_SYS_PIN);  //LED翻转
 //               i = 0;
 //           }
            CAT1_MAIN_DTR_set(ON);//重新拉高，防止CAT1进不了低功耗
            Debug_Printf("\r\nRTC doki wakeup...\r\n");
        }
       
        //通过检测到有红外源的中断触发，需要主动唤醒模块进入传输
        if (QG_state_start == 1)
        {
            if (pre_QG_state == 0)
            {
               
                CAT1_MAIN_DTR_set(OFF);//拉低唤醒CAT1模组
                delay1ms(55);
                if (sendCommand("AT\r\n", "OK", 10, 2))
                {
                    getIMEI();
                    memset(dataToSend, 0, SEND_MAX_LEN);
                    uint8_t len = snprintf(dataToSend, SEND_MAX_LEN, 
                    "{\"disperse_state\":%d, \"IMEI\":\"%s\"}", 
                    1, device_imei);
                    if (NT26K_SendData("warning_flag", dataToSend))
                    {
                        QG_state_start = 0; //重置状态
                        pre_QG_state = 1;
                    }
                    QG_state_start = 0; //重置状态
                    pre_QG_state = 1;
                    CAT1_state_low_power = 0;            
                 //    Debug_Printf("\r\nsend warning:%s\r\n", dataToSend);
                }
                CAT1_MAIN_DTR_set(ON);
             //    Debug_Printf("hongwai wake up CAT1 suc\r\n");
                // Gpio_SetIO(APP_LED_SYS_PORT, APP_LED_SYS_PIN); //LED亮起
            }else
            {
                //如果上一次状态是开启则跳过这一次上传
                QG_state_start = 0; //重置状态
                CAT1_MAIN_DTR_set(ON);
            }
           
        }
        //发送恢复包，需要主动唤醒模块进入传输
        boolean_t start_state = QG_getStateStart();
        Debug_Printf("\r\nstart_state: %d\r\n", start_state);
        if (start_state == 0 && pre_QG_state == 1)
        {
             QG_info.state = 0; //恢复状态
            //  QG_state_recover = 0; //重置状态
            //  pre_QG_state = 0;

            //  CAT1_state_low_power = 0;

            //  CAT1_MAIN_DTR_set(ON);
            CAT1_MAIN_DTR_set(OFF);//拉低唤醒CAT1模组
            delay1ms(55);
            if (sendCommand("AT\r\n", "OK", 10, 2))
            {
             //    Debug_Printf("wake up CAT1 suc\r\n");
                getIMEI();
                memset(dataToSend, 0, SEND_MAX_LEN);
                uint8_t len = snprintf(dataToSend, SEND_MAX_LEN, 
                "{\"disperse_state\":%d, \"IMEI\":\"%s\"}", 
                0, device_imei);
                if (NT26K_SendData("warning_flag", dataToSend))
                {
                    QG_state_recover = 0; //重置状态
                    pre_QG_state = 0;
                }
                CAT1_state_low_power = 0;            
             //    Debug_Printf("\r\nsend warning:%s\r\n", dataToSend);
            }
            CAT1_MAIN_DTR_set(ON);
            // Gpio_ClrIO(APP_LED_SYS_PORT, APP_LED_SYS_PIN); //LED熄灭
        }
        if (reset_flag == 1)
        {
             NVIC_SystemReset();
             // SCB->AIRCR  = 0X05FA0004; 
             while(1)
             {
                ;
             }
        }
       
 //        delay1ms(1000);
 //        NT26K_sendDeviceSignal();
        
 #ifdef LOW_POWER_ENABLE
        QG_set_low_power();      //进入低功耗模式
 #endif
       
    }
 }







/******************************************************************************
 * EOF (not truncated)
 ******************************************************************************/


